﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsService1
{
    public class LoadingRobotDataProcessor
    {
        private Dictionary<string, RobotActionData> _lastActionData = new Dictionary<string, RobotActionData>();
        private string _lastRobotStatus;
        private string _lastHandStatus;
        private readonly MqttTopicLogger _mqttTopicLogger = MqttTopicLogger.Instance;
        private readonly string _robotName;
        private readonly string _uploadMode;

        public LoadingRobotDataProcessor(string robotName, string uploadMode)
        {
            _robotName = robotName; // 使用配置中的RobotName
            _uploadMode = uploadMode;
        }

        public (bool hasChanges, string jsonData) ProcessRobotData(Dictionary<string, short> plcData)
        {
            var sw = Stopwatch.StartNew();
            _mqttTopicLogger.WriteSystemInfo("开始处理上料机械臂数据");

            try
            {
                // 1. 获取当前机械臂和夹爪状态
                var currentRobotStatus = plcData["Robot_Status"].ToString();
                var currentHandStatus = plcData["Gripper_Status"].ToString();

                // 2. 检测当前激活的动作
                var currentAction = DetectCurrentAction(plcData);
                var currentTimepoint = GetCurrentTimepoint(plcData, currentAction);

                // 3. 检查状态是否变化
                bool statusChanged = currentRobotStatus != _lastRobotStatus ||
                                   currentHandStatus != _lastHandStatus ||
                                   !string.IsNullOrEmpty(currentAction) &&
                                   (!_lastActionData.ContainsKey(currentAction) ||
                                    _lastActionData[currentAction].Timepoint != currentTimepoint);

                if (!statusChanged)
                {
                    sw.Stop();
                    _mqttTopicLogger.WritePerformanceMetric("机械臂数据处理", sw.ElapsedMilliseconds, "ms");
                    return (false, null);
                }

                // 4. 准备JSON数据
                var jsonData = new
                {
                    device_time = DateTime.Now.ToString("yyyyMMddHHmmssffffff"),
                    robot_name = _robotName,
                    robot_status = currentRobotStatus,
                    action = currentAction,
                    timespan = GetActionTimespan(currentAction).ToString("0.0"),
                    upload_mode = _uploadMode,
                    timepoint = currentTimepoint.ToString("0.0"),
                    hand_status = currentHandStatus
                };

                string jsonString = JsonConvert.SerializeObject(jsonData);

                // 5. 更新最后状态
                _lastRobotStatus = currentRobotStatus;
                _lastHandStatus = currentHandStatus;

                if (!string.IsNullOrEmpty(currentAction))
                {
                    _lastActionData[currentAction] = new RobotActionData
                    {
                        Action = currentAction,
                        Timepoint = currentTimepoint
                    };
                }

                sw.Stop();
                _mqttTopicLogger.WriteSystemInfo($"生成机械臂JSON数据: {jsonString}");
                _mqttTopicLogger.WritePerformanceMetric("机械臂JSON生成", sw.ElapsedMilliseconds, "ms");

                return (true, jsonString);
            }
            catch (Exception ex)
            {
                _mqttTopicLogger.WriteSystemError($"处理机械臂数据错误: {ex.Message}", ex);
                return (false, null);
            }
        }

        private string DetectCurrentAction(Dictionary<string, short> plcData)
        {
            // 检测哪个动作被激活（A-H）
            foreach (var action in new[] { "A", "B", "C", "D", "E", "F", "G", "H" })
            {
                if (plcData.TryGetValue(action, out short value) && value == 1)
                {
                    return action;
                }
            }
            return "";
        }

        private float GetCurrentTimepoint(Dictionary<string, short> plcData, string action)
        {
            if (string.IsNullOrEmpty(action) || _uploadMode == "A")
            {
                return 0; // 模式A或没有动作时返回0
            }

            // 从PLC数据中读取时间组件并计算时间点
            if (plcData.TryGetValue($"{action}_Hour", out short hour) &&
                plcData.TryGetValue($"{action}_Min", out short min) &&
                plcData.TryGetValue($"{action}_Sec", out short sec) &&
                plcData.TryGetValue($"{action}_MSec", out short msec))
            {
                // 计算当前动作已执行的时间（秒）
                float currentTime = hour * 3600 + min * 60 + sec + msec / 1000f;

                // 如果是第一次记录这个动作，返回0
                if (!_lastActionData.ContainsKey(action))
                {
                    return 0;
                }

                // 计算时间差
                float timepoint = currentTime - _lastActionData[action].StartTime;
                float timespan = GetActionTimespan(action);

                // 确保时间点在合理范围内
                return Math.Min(timepoint, timespan);
            }

            return 0;
        }

        private float GetActionTimespan(string action)
        {
            // 预定义各动作的标准时间（秒）
            var timespanMap = new Dictionary<string, float>
        {
            { "A", 1.5f },
            { "B", 0.5f },
            { "C", 1.5f },
            { "D", 2.5f },
            { "E", 1.5f },
            { "F", 0.5f },
            { "G", 1.5f },
            { "H", 2.5f }
        };

            return timespanMap.TryGetValue(action, out float timespan) ? timespan : 0;
        }

        private class RobotActionData
        {
            public string Action { get; set; }
            public float Timepoint { get; set; }
            public float StartTime { get; set; } // 用于计算时间差
        }
    }
}
